package com.fcl.oschina.model;

import com.fcl.mylibrary.http.HttpClient;
import com.fcl.mylibrary.util.FLog;
import com.fcl.mylibrary.util.StringUtil;
import com.fcl.oschina.Constant;
import com.fcl.oschina.entity.BaseReturn;
import com.fcl.oschina.entity.ImageEntity;
import com.fcl.oschina.entity.ListResult;
import com.fcl.oschina.entity.NewItem;
import com.fcl.oschina.entity.TweetEntity;
import com.fcl.oschina.ui.fragment.NewsView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/3/15.
 */

public class NewsModel {

    private String TAG = "NewsModel";
    private NewsView mNewsView;
    private String  mNextPage="";

    public NewsModel(NewsView newsView) {
        this.mNewsView = newsView;
    }

    public void setNextPage(String mNextPage) {
        this.mNextPage = mNextPage;
    }

    public void getBanner(int catalog) {
        String url = Constant.BASE_URL+"action/apiv2/banner?catalog="+catalog;
        HttpClient client = new HttpClient(url, new HttpClient.ResultListener() {
            @Override
            public void dealResult(String result) {
                Gson gson = new Gson();
                BaseReturn baseReturn = gson.fromJson(result, new TypeToken<BaseReturn<ListResult<ImageEntity>>>(){}.getType());
                if (baseReturn.getCode() == 1) {
                    FLog.error(TAG, "success thread"+Thread.currentThread().getId());
                    ListResult<ImageEntity> data = (ListResult<ImageEntity>) baseReturn.getResult();
                    List<String> bannerDatas = new ArrayList<>();
                    for (ImageEntity imagesBean : data.getItems()) {
                        bannerDatas.add(imagesBean.getImg());
                    }
                    mNewsView.setBanner(bannerDatas);
                }
            }
        });
        client.get();
    }

    public void getNewsList() {
//        if (!NetWorkUtils.isConnectedByState(AppContext.getInstance())) {
//            mNewsView.noNet();
//            return;
//        }

        String url = Constant.BASE_URL+"action/apiv2/news?pageToken="+mNextPage;
        HttpClient client = new HttpClient(url, new HttpClient.ResultListener() {
            @Override
            public void dealResult(String result) {
                Gson gson = new Gson();
                BaseReturn baseReturn = gson.fromJson(result, new TypeToken<BaseReturn<ListResult<NewItem>>>(){}.getType());
                if (baseReturn.getCode() == 1) {
                    FLog.error(TAG, "success thread"+Thread.currentThread().getId());
                    ListResult<NewItem> data = (ListResult<NewItem>) baseReturn.getResult();

                    mNewsView.setData(data.getItems(), !StringUtil.isEmpty(mNextPage));
                    mNextPage = data.getNextPageToken();
                }
            }
        });
        client.get();

    }

}
